// 封装关注的代码逻辑
import {
  cancelOrder,
  deleteOrder,
  followOrUnFollow,
  getPrescriptionPic
} from '@/services/consult'
import { onMounted, ref } from 'vue'

import type { ConsultOrderItem, FollowType } from '@/types/consult'
import { showFailToast, showImagePreview, showSuccessToast } from 'vant'
import { OrderType } from '@/enums'
import type { OrderDetail } from '@/types/order'
import { getMedicalOrderDetail } from '@/services/order'
export const useFollow = (type: FollowType = 'doc') => {
  const loading = ref(false)
  // 类型兼容 Doctor / Knowledge- 多的可以给少的
  const follow = async (item: { id: string; likeFlag: 0 | 1 }) => {
    // 1. 按钮状态 - 加载中
    // 2. 更新按钮文本 - 已关注 or 未关注
    // 3. 关注成功or关注失败(网络原因) 需要将按钮的loading状态改为false
    loading.value = true
    try {
      await followOrUnFollow(item.id, type)
      item.likeFlag = item.likeFlag === 1 ? 0 : 1
    } finally {
      // 成功还是失败, 都会执行
      loading.value = false
    }
  }

  return {
    loading,
    follow
  }
}

export const usePrescriptionPic = () => {
  // 预览处方图片
  const showPrescriptionPic = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionPic(id)
      showImagePreview([res.data.url])
    }
  }
  return {
    showPrescriptionPic
  }
}

export const useCancelOrder = () => {
  const loading = ref(false)
  // 取消订单
  const onCancel = async (item: ConsultOrderItem) => {
    loading.value = true
    // 开启loading效果
    // 成功 - 修改订单状态 + 状态value + 提示用户
    // 失败 - 提示用户
    // ....关闭loading效果
    try {
      await cancelOrder(item.id)
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
      showSuccessToast('取消成功')
    } catch (error) {
      showFailToast('取消失败')
    } finally {
      loading.value = false
    }
  }
  return {
    loading,
    onCancel
  }
}

export const useDeleteOrder = (callback?: () => void) => {
  const loading = ref(false)
  const onDelete = async (item: ConsultOrderItem) => {
    loading.value = true
    try {
      await deleteOrder(item.id)
      // // 派发事件 - 通知父组件
      // emit('on-delete', item.id)
      // 成功后的业务处理
      // 问诊列表 - 通知父组件
      // 问诊详情 - 跳转
      // .....  -
      callback && callback()
      showSuccessToast('删除成功')
    } catch (error) {
      showFailToast('删除失败')
    } finally {
      loading.value = false
    }
  }
  return {
    loading,
    onDelete
  }
}

export const useOrderDetail = (id: string) => {
  const order = ref<OrderDetail>()
  const loading = ref(false)
  const getOrderDetail = async () => {
    try {
      loading.value = true
      const res = await getMedicalOrderDetail(id)
      order.value = res.data
    } finally {
      loading.value = false
    }
  }
  onMounted(() => {
    getOrderDetail()
  })
  return { order, loading }
}
